<template>
	<div class="container">
		<h2 style="text-align: center;margin-bottom: 30px;">出场确认</h2>
		<a-form ref="formRef" :model="formState" @finish="handleSave">
			<h3>验收单信息</h3>
			<a-row :gutter="20">
				<a-col :span="12">
					<a-form-item label="项目名称">{{ project.name??'' }}</a-form-item>
				</a-col>

				<a-col :span="12">
					<a-form-item label="供应商名称">{{ supplier.company_name??'' }}</a-form-item>
				</a-col>

				<a-col :span="12">
					<a-form-item label="验收单编号">{{ route.query.code }}</a-form-item>
				</a-col>

				<a-col :span="12">
					<a-form-item label="发货单编号">{{ formState.code }}</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="接收信息">
						接收地点：{{ formState.deliver_address }} &nbsp;&nbsp;&nbsp;&nbsp;
						接收时间：{{ formState.deliver_time }}&nbsp;&nbsp;&nbsp;&nbsp;
						接收人：{{ formState.receiver }} &nbsp;&nbsp;&nbsp;&nbsp;
						联系电话：{{ formState.receiver_tel }}
					</a-form-item>
				</a-col>

				<a-col :span="24">
					<a-table :pagination="false" :data-source="formState.materials" :columns="purchaseColumns" :row-key="(record) => record.key">
						<template #bodyCell="{ column,index }">
							<template v-if="column.dataIndex === 'id'">{{ index+1 }}</template>
							<template v-else-if="column.dataIndex === 'exit_time'">
								<a-form-item :name="['materials', index, 'adexit_timed_time']">
									<a-date-picker v-model:value="formState.materials[index]['exit_time']" show-time placeholder="请输入出场时间" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'use_time'">
								<a-form-item :name="['materials', index, 'use_time']" :rules="{required:true, message:'请输入使用时长'}">
									<a-input v-model:value="formState.materials[index].use_time" type="number" min="1" placeholder="请输入使用时长" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'time_unit'">
								<a-form-item :name="['materials', index, 'time_unit']" :rules="{required:true, message:'请选择时长计量单位'}">
									<a-select v-model:value="formState.materials[index].time_unit" :show-search="true" placeholder="请选择时长计量单位" :options="timeunitOptions" :field-names="{value:'name'}" style="width:100%" :disabled="formState.ys_type === 3"></a-select>
								</a-form-item>
							</template>
						</template>
					</a-table>
				</a-col>
			</a-row>
			<a-row v-if="realFileList.length" :gutter="24">
				<a-col :span="24" class="py-4 text-right">
					<a-form-item label="发货附件" name="real_pic_path">
						<template v-for="item in realFileList" :key="item.url">
							<a target="_blank" :href="item.url">{{ item.name }}</a><br />
						</template>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row v-if="realPicList.length" :gutter="24">
				<a-col :span="24" class="py-4 text-right">
					<a-form-item label="发货图片" name="real_pic_path"></a-form-item>
				</a-col>
				<a-col v-for="item in realPicList" :key="item.url" :span="6">
					<div class="gallery-image">
						<a-image :width="160" :height="160" :src="item.url" />
					</div>
					<p>{{ item.name }}</p>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="8" class="py-4 text-center">
					<a-form-item label="选择验收类型" name="ys_type" :rules="{required:true, message:'请选择验收类型'}">
						<a-select v-model:value="formState.ys_type" :show-search="true" placeholder="请选择验收类型" :options="yslist" option-filter-prop="label" disabled></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="8" class="py-4 text-right">
					<a-form-item label="验收图片" name="pic_path" :rules="{required:true, message:'请上传验收图片'}">
						<a-upload v-model:file-list="formState.pic_path" name="upload" :action="`${baseURL}/contract/upload`" accept=".jpg, .jpeg, .png" disabled :show-upload-list="true" :headers="{Authorization:`Bearer ${proxy.$cookies.get('token')}`}" :before-upload="picbeforeUpload" @change="picchangeUpload">
							<a-button>
								<template v-if="pic_uploading">
									<loading-outlined />上传中...
								</template>
								<template v-else>
									<import-outlined />上传验收图片
								</template>
							</a-button>
						</a-upload>
					</a-form-item>
				</a-col>
				<a-col :span="8" class="py-4 text-right">
					<a-form-item label="验收视频" name="video_path">
						<a-upload v-model:file-list="formState.video_path" accept=".mp4" name="upload" :action="`${baseURL}/contract/upload`" disabled :show-upload-list="true" :headers="{Authorization:`Bearer ${proxy.$cookies.get('token')}`}" :before-upload="videobeforeUpload" @change="videochangeUpload">
							<a-button>
								<template v-if="video_uploading">
									<loading-outlined />上传中...
								</template>
								<template v-else>
									<import-outlined />上传验收视频
								</template>
							</a-button>
						</a-upload>
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<a-form-item label="验收描述" name="ys_des">
						<a-input v-model:value="formState.ys_des" disabled />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<a-button v-if="formState.ys_type>0" type="primary" html-type="submit">
							<save-outlined />出场确认
						</a-button>

						<a-button @click="closeTab('/yanshou/log')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { Modal } from "ant-design-vue";
import { DeleteOutlined, SaveOutlined, CloseOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { post } from "../utils";
import { baseURL } from "../utils/request";
import { useRoute } from "vue-router";
import dayjs from "dayjs";
const route = useRoute();
const formState = ref({ materials: [] });
const formRef = ref();
const { proxy } = getCurrentInstance();
const yslist = [
	{ value: 1, label: "钢筋" },
	{ value: 2, label: "混凝土" },
	{ value: 3, label: "周转材料" },
	{ value: 4, label: "机械" },
	{ value: 5, label: "其它" },
	{ value: 6, label: "辅助材料" }
];
const realPicList = ref([]);
const realFileList = ref([]);
const timeunitOptions = ref([]);
post("dictionary", { root_code: "MATERIAL_TIMEUNIT" }).then(data => {
	timeunitOptions.value = data;
});
const purchaseColumns = [
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "物资名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		align: "center",
	},
	{
		title: "采购数量",
		dataIndex: "quantity",
		align: "center",
	},
	{
		title: "发货数量",
		dataIndex: "real_quantity",
		align: "center"
	},
	{
		title: "验收数量",
		dataIndex: "ys_quantity",
		align: "center"
	},
	{
		title: "进场时间",
		dataIndex: "enter_time",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	// {
	// 	title: "出场时间",
	// 	dataIndex: "exit_time",
	// 	align: "center",
	// 	customRender: ({ text, record, index, column }) => {
	// 		return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
	// 	}
	// },
	{
		title: "使用时长",
		dataIndex: "use_time",
		align: "center"
	},
	// {
	// 	title: "时长单位",
	// 	dataIndex: "time_unit",
	// 	align: "center"
	// },
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
];

// 物资信息
const purchaseOrderInfo = ref({});
const project = ref({});
const supplier = ref({});

const id = computed(() => route.params.id);
const type = ref();
onMounted(() => {
	post(`supplyOrder/info`, { id: id.value }).then(data => {
		data.pic_path = JSON.parse(data.pic_path || "[]");
		data.video_path = JSON.parse(data.video_path || "[]");
		data.real_pic_path = JSON.parse(data.real_pic_path || "[]");
		for (const file of data.real_pic_path) {
			const suffix = file.url.split(".").pop();
			if (['jpg', 'jpeg', 'png'].includes(suffix)) {
				realPicList.value.push(file)
			} else {
				realFileList.value.push(file);
			}
		}
		data.materials = data.materials.map(item => {
			const { quantity, unit, memo, use_date, time_unit, fangliang, luodu, changdu, add_time, part, real_quantity, ys_quantity, enter_time, exit_time } = item.SupplyOrderMaterial;
			const use_time = Math.ceil((new Date().getTime() - new Date(enter_time).getTime()) / 1000 / 60 / 60 / 24);
			return {
				...item,
				quantity,
				unit,
				memo,
				use_date,
				use_time,
				time_unit: (data.ys_type === 3 ? '天' : time_unit),
				fangliang,
				luodu,
				changdu,
				part,
				real_quantity,
				ys_quantity,
				enter_time,
				exit_time,
				add_time: dayjs(add_time).format("YYYY-MM-DD HH:mm:ss")
			};
		});
		type.value = data.purchaseOrder.type;
		const purchaseOrder = data.purchaseOrder;
		purchaseOrder.create_time = dayjs(purchaseOrder.create_time).format("YYYY-MM-DD HH:mm:ss");
		purchaseOrderInfo.value = purchaseOrder;
		project.value = data.project;
		supplier.value = data.supplier;
		data.ys_type = parseInt(data.ys_type);
		formState.value = data;
	});
});
//上传前校验
const pic_uploading = ref(false);
const video_uploading = ref(false);
const picbeforeUpload = file => {
	pic_uploading.value = true;
};
// 上传并提交文件
const picchangeUpload = ({ file }) => {
	if (file.status === "done") {
		formState.value.pic_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];
		formState.value.pic_path = formState.value.pic_path.filter((item) => item.url);
		pic_uploading.value = false;
		proxy.$message.success("验收图片上传成功");
	}
	if (!file.status) {
		formState.value.pic_path = formState.value.pic_path.filter((item) => item.url);
	}
};
//上传前校验
const videobeforeUpload = file => {
	video_uploading.value = true;
};
// 上传并提交文件
const videochangeUpload = ({ file }) => {
	if (file.status === "done") {
		formState.value.video_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];
		formState.value.video_path = formState.value.video_path.filter((item) => item.url);
		video_uploading.value = false;
		proxy.$message.success("验收视频上传成功");
	}
	if (!file.status) {
		formState.value.video_path = formState.value.video_path.filter((item) => item.url);
	}
};
const handleSave = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			let has_error = 0;
			const materials = formState.value.materials.map(item => {
				item.ys_quantity = parseFloat(item.ys_quantity);
				item.real_quantity = parseFloat(item.real_quantity);
				if (item.ys_quantity <= 0) {
					proxy.$message.error("请输入验收数量");
					has_error = 1;
				} else if (parseFloat(item.ys_quantity) > parseFloat(item.real_quantity)) {
					proxy.$message.error("验收数量不能超过发货数量");
					has_error = 1;
				}
				let exit_time;
				if ([3, 4].includes(formState.value.ys_type)) {
					exit_time = dayjs(item.enter_time).add(item.use_time, "day").format("YYYY-MM-DD HH:mm:ss")
				}
				return {
					id: item.SupplyOrderMaterial.id,
					material_id: item.SupplyOrderMaterial.material_id,
					ys_quantity: item.ys_quantity,
					exit_time,
					use_time: item.use_time,
					time_unit: item.time_unit
				};
			});
			if (has_error) {
				return false;
			}
			const params = {
				materials: JSON.stringify(materials),
				id: id.value,
				ys_type: formState.value.ys_type,
				pic_path: JSON.stringify(formState.value.pic_path),
				video_path: JSON.stringify(formState.value.video_path),
				ys_des: formState.value.ys_des,
				opr_type: "exit"
			};

			Modal.confirm({
				title: "操作确认?",
				content: "您确定要出场吗，请确认",
				onOk() {
					post("supplyOrder/save", params)
						.then(() => {
							proxy.$message.success("操作成功", 1);
							closeTab("/yanshou/log");
						})
						.catch(err => {
							proxy.$message.error(err);
						});
				}
			});
		})
		.catch(err => {
			proxy.$message.error(err.message);
		});
};

const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 20px;

	:deep(.ant-table-cell) .ant-form-item {
		margin-bottom: 0;

		.ant-form-item-explain {
			position: absolute;
			bottom: -24px;
		}
	}
}

:deep(.ant-input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
:deep(.ant-input-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
//
:deep(.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
:deep(.ant-radio-disabled + span) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
}
</style>
